<?php


namespace App\Services;


use App\Facades\Sms;
use App\Models\Member;
use Overtrue\EasySms\Message;

class NotificationService extends BaseService
{
    public static function fire($acceptUuid, array $params, Message $oMessage = null)
    {
        $messageTitle   = '系统通知';
        $messageContent = '';

        if (!$acceptUuid) {
            throw new \Exception('用户uuid必传');
        }

        // 待接收消息人
        $oMember = Member::query()
            ->where('uuid', $acceptUuid)
            ->where('status', 1)
            ->firstOrFail();

        $userPlatform = $oMember->user_platform;
        if (!in_array($userPlatform, array_keys(Member::USER_PLATFORMS))) {
            throw new \Exception('用户终端类型非法');
        }

        // @step1 若user_platform为微信小程序，则调用发送短信
        if ($userPlatform == Member::USER_PLATFORM_WXXCX) {
            Sms::send($oMember->phone, $oMessage);
            return;
        }

        // @step2 若user_platform为原生app，则调用umeng推送
        try {
            $roleId        = $oMember->role_id;
            $umengPushType = ''; // 选择推送司机端或货主端
            switch ($roleId) {
                case Member::ROLE_DRIVER:
                    $umengPushType = 'driver';
                    break;
                case Member::ROLE_ORDER: // 发单人
                case Member::ROLE_SHIPPER: // 发货人
                case Member::ROLE_RECEIVER: // 收货人
                case Member::ROLE_FINANCE: // 财务
                    $umengPushType = 'owner';
                    break;
            }

            $umengService = new UmengService($umengPushType);
            switch ($userPlatform) {
                case Member::USER_PLATFORM_ANDROID:
                    $umengService->paramsBuilder($params)->androidCustomizedCast();
                    break;
                case Member::USER_PLATFORM_IOS:
                    $umengService->paramsBuilder($params)->iosCustomizedCast();
                    break;
            }

            // @step3 若是发单人，还需要发送站内信
            $roleId == Member::ROLE_ORDER && MessageService::fallbackUmeng($messageTitle, $messageContent, $acceptUuid);

        } catch (\Exception $e) {
            // 若是 发货人、收货人和财务，消息推送失败时，使用短信推送，同时有站内信
            if (in_array($roleId, [Member::ROLE_SHIPPER, Member::ROLE_RECEIVER])) {
                Sms::send($oMember->phone, $oMessage); //短信推送
                MessageService::fallbackUmeng($messageTitle, $messageContent, $acceptUuid); // 站内信
            }
        }
    }
}